package bounjour;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.List;

public class Comment extends IObjectFactory {

	private int id;
	public int getID() { return id; }

	private int postID;
	public int getPostID() { return postID; }

	private int type;
	public int getType() { return type; }
	
	private java.util.Date createDate;
	public java.util.Date getCreateDate() { return createDate; }

	private String body;
	public String[] getBody() { return body.split("\t"); }
	
	private int userId;
	public int getUserID() { return userId; }
	public void setUserID(int value) { userId = value; }
	
	private String userName;
	public String getUserName() {
		return userName;
	}
	
	public Comment() {}
	
	public Comment(int postID) {
		this.postID = postID;
	}
	
	public void buildFromReader(java.sql.ResultSet RS) {
		try {
			this.id = RS.getInt("ID");
			this.createDate = RS.getDate("CreateDate");
			this.body = RS.getString("Body");
			this.userId = RS.getInt("UserID");
			try {
				this.userName = RS.getString("UserName");
			} catch (Exception e0) {}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public void addData(int fieldID, String value) {
		if (body == null) body = value;
		else body = body + "\t" + value;
	}

	public void save() {
		Connection cn = null;
		java.sql.PreparedStatement ps = null;
		
	    try{
	    	cn = getConnection();
	    	if (this.id == 0) { // create	    		
			    ps = cn.prepareStatement("INSERT INTO Comments (Body,UserID,CreateDate,PostID,Type) VALUES (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
			    ps.setString(1, this.body);
			    ps.setInt(2, this.getUserID());
			    ps.setDate(3, new java.sql.Date(new Date().getTime()));
			    ps.setInt(4, this.getPostID());
			    ps.setInt(5, this.getType());
			    
			    ps.execute();
			    ResultSet rs = ps.getGeneratedKeys();
			    if (rs.next()) this.id = rs.getInt(1);
			    rs.close();
	    	}
	    	else { // update
	    		ps = cn.prepareStatement("UPDATE Comments SET Body=?,CreateDate=?) WHERE ID=?");
			    ps.setString(1, this.body);
			    ps.setDate(3, new java.sql.Date(new Date().getTime()));
			    ps.setInt(4, this.getID());
			    ps.execute();
	    	}
	    	cn.close();
	    	ps.close();
	    }
	    catch (Exception sqlEx){
	      System.err.println(sqlEx);
	    }			
	}
	
	static public List<Comment> getComments(int postID) {
		return getObjectList(Comment.class, "SELECT Comments.*, Users.DisplayName AS UserName FROM Comments INNER JOIN Users ON Comments.UserID=Users.ID WHERE PostID=? ORDER BY Comments.ID DESC;", postID);
	}
	
}
